package com.tangcco.lockwell.controller.student;

import com.tangcco.lockwell.base.RestResponse;
import com.tangcco.lockwell.context.WebContext;
import com.tangcco.lockwell.domain.Message;
import com.tangcco.lockwell.domain.MessageLikesRecord;
import com.tangcco.lockwell.service.MessageLikesRecordService;
import com.tangcco.lockwell.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * 用户消息点赞记录
 * @author yanxinping
 * @version 1.0
 * @description: TODO
 * @date 2024/12/24 9:34
 */
@RestController
@RequestMapping("/api/student/messageLikesRecord")
public class MessageLikesRecordController {

    @Autowired
    private MessageLikesRecordService messageLikesRecordService;
    @Autowired
    private WebContext webContext;
    @Autowired
    private MessageService messageService;
    /**
     * 添加用户点赞记录或取消点赞
     * @return
     */
    @RequestMapping("/addOrCancelMessageLikesRecord")
    @Transactional
    public RestResponse addMessageLikesRecord(@RequestParam("messageId") Integer messageId,
                                              @RequestParam("flag") Integer flag) {
        //flag=1为点赞，flag=0为取消点赞
        if (flag == 1) {
            messageLikesRecordService.addLikesRecord(webContext.getCurrentUser().getUserId(), messageId);
            //点赞数+1
            Message message = messageService.findById(messageId);
            if(message!=null){
                message.setLikes(message.getLikes()+1);
                //父级点赞数+1
                Message parentMessage = messageService.findById(Integer.parseInt(message.getBelongs()));
                if(parentMessage!=null){
                     parentMessage.setLikes(parentMessage.getLikes()+1);
                     messageService.updateMessage(parentMessage);
                }
            }
            messageService.updateMessage(message);
        } else {
            messageLikesRecordService.deleteLikesRecord(webContext.getCurrentUser().getUserId(), messageId);
            //点赞数-1
            Message message = messageService.findById(messageId);
            if(message!=null){
                message.setLikes(message.getLikes()-1);
                //父级点赞数-1
                Message parentMessage = messageService.findById(Integer.parseInt(message.getBelongs()));
                if(parentMessage!=null){
                    parentMessage.setLikes(parentMessage.getLikes()-1);
                    messageService.updateMessage(parentMessage);
                }
            }
            messageService.updateMessage(message);
        }

        return RestResponse.ok();
    }


}
